package com.sso.portal.controller;

import com.sso.common.dto.ApiResponse;
import com.sso.common.entity.User;
import com.sso.common.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class PortalController {

    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/")
    public String home(Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            if (authentication instanceof OAuth2AuthenticationToken) {
                OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
                OAuth2User oauth2User = oauthToken.getPrincipal();
                
                // 获取用户信息
                String username = oauth2User.getAttribute("sub");
                String email = oauth2User.getAttribute("email");
                
                // 创建用户对象
                User user = new User();
                user.setUsername(username);
                user.setEmail(email);
                
                // 生成JWT令牌
                String token = JwtUtil.generateToken(user);
                
                // 将令牌存储到Redis，设置过期时间
                redisTemplate.opsForValue().set("token:" + username, token, 24, TimeUnit.HOURS);
                
                // 将用户信息和令牌添加到模型
                model.addAttribute("user", user);
                model.addAttribute("token", token);
                
                // 构建OA和风控系统的URL，包含令牌
                String oaSystemUrl = "http://www.oauth2server.com:8080/sso?token=" + token;
                String riskControlSystemUrl = "http://www.oauth2server.com:8081/sso?token=" + token;
                
                model.addAttribute("oaSystemUrl", oaSystemUrl);
                model.addAttribute("riskControlSystemUrl", riskControlSystemUrl);
            }
        }
        return "index";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/user-info")
    @ResponseBody
    public ApiResponse<Map<String, Object>> getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Map<String, Object> userInfo = new HashMap<>();
        
        if (authentication != null && authentication.isAuthenticated()) {
            if (authentication instanceof OAuth2AuthenticationToken) {
                OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
                OAuth2User oauth2User = oauthToken.getPrincipal();
                
                userInfo.put("username", oauth2User.getAttribute("sub"));
                userInfo.put("email", oauth2User.getAttribute("email"));
                userInfo.put("name", oauth2User.getAttribute("name"));
                
                // 获取访问令牌
                OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(
                    oauthToken.getAuthorizedClientRegistrationId(),
                    oauthToken.getName()
                );
                
                if (client != null) {
                    userInfo.put("accessToken", client.getAccessToken().getTokenValue());
                    if (client.getRefreshToken() != null) {
                        userInfo.put("refreshToken", client.getRefreshToken().getTokenValue());
                    }
                }
            } else {
                userInfo.put("username", authentication.getName());
            }
            return ApiResponse.success(userInfo);
        }
        
        return ApiResponse.error("用户未认证");
    }
}